package com.sky.service.impl;

import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增收货地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBookMapper.add(addressBook);
    }

    /**
     * 查询登录用户所有地址
     * @return
     */
    @Override
    public List<AddressBook> getAddressByUserId() {
        List<AddressBook> addressBookList = addressBookMapper.getAddressByUserId(0L);

        return addressBookList;
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        AddressBook addressBook=AddressBook.builder()
                                .isDefault(1)
                                .build();

        AddressBook address = addressBookMapper.getAddress(addressBook);

        return address;
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteAddressById(Long id) {
        addressBookMapper.deleteAddressById(id);
    }


    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressById(Long id) {
        AddressBook addressBook=AddressBook.builder()
                                .id(id)
                                .build();

        addressBook= addressBookMapper.getAddress(addressBook);

        return addressBook;
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefaultAddress(AddressBook addressBook) {
          //把当前用户的地址设置为非默认
          AddressBook addressBook1=new AddressBook();
          addressBook1.setIsDefault(0);
          addressBookMapper.updateAddress(addressBook1);

          //将当前地址改为默认地址
          addressBook.setIsDefault(1);
          addressBookMapper.updateAddress(addressBook);
    }
}
